package com.example.controller;

import com.example.entity.ResponseEntity;
import com.example.service.impl.ShortMsgServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务控制类
 * @author 李平
 * @Date 2022-5-1
 */
@RestController
public class ShortMsgController {

    @Autowired
    private ShortMsgServiceImpl shortMsgService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final Logger LOG = LoggerFactory.getLogger(ShortMsgController.class);

    /**
     * 短信验证码
     * @param phone
     * @return ResponseEntity
     */
    @GetMapping
    @RequestMapping("/getShortCode/{phone}/{id}")
    public ResponseEntity sengMsgCode(@PathVariable(name="phone") String phone, @PathVariable(name="id") String id) {
        // 从Redis中取出已存在的验证码
        String p = redisTemplate.opsForValue().get(phone + "-" + id);
        if (!StringUtils.isEmpty(p)) {
            if ("0".equals(id)){
                LOG.warn("学生角色：" + phone + ": " + p + "已存在，还未过期");
            }else if ("2".equals(id)){
                LOG.warn("评审人员角色：" + phone + ": " + p + "已存在，还未过期");
            }
            return ResponseEntity.err("验证码已存在，还未过期",p);
        }
        // 生成随机验证码
        String code = UUID.randomUUID().toString().substring(0, 6);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        // 发送验证码到手机
        Boolean b = shortMsgService.sendShortMsg(phone,map);
        if (b) {
            // 发送成功，将此验证码存入Redis，并设置过期时间为5分钟
            redisTemplate.opsForValue().set(phone + "-" + id,code,300,TimeUnit.SECONDS);
            if ("0".equals(id)){
                LOG.info("学生角色：" + "验证码发送成功" + code);
            }else if ("2".equals(id)){
                LOG.info("评审人员角色：" + "验证码发送成功" + code);
            }
            return ResponseEntity.ok(code);
        } else {
            LOG.error("验证码发送失败");
            return ResponseEntity.err("发送失败");
        }
    }

}
